package main

import (
	"config/model"
	"flag"
	"github.com/fsnotify/fsnotify"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"time"
	"utilsx/ginRoute"
	"utilsx/pkg/ginMiddleware"
	"utilsx/tools/fileUtils"
	"utilsx/tools/jwtMinddle"
	db "webFull/config"
	"webFull/internal/middleware"
	"webFull/internal/service"
	"webFull/router"
)

//go install github.com/swaggo/swag/cmd/swag@latest
import (
	"context"
	_ "net/http/pprof"
	"os/signal"
)

var srv *http.Server

func SetGinEngine() {
	flag.Parse()
	engine := ginRoute.NewDefaultEngine()
	engine.UseMiddleware(middleware.Logger(), ginMiddleware.Cors(), middleware.AuthRequired())
	engine.AddGroupServers(
		router.RootPath(),
		router.Admin(),
		router.Game(),
		router.Email(),
		router.User(),
	)
	jwtMinddle.JwtIgnore.AddKey("/", "assets", "static", "favicon.ico")
	// 前端项目静态资源
	//engine.GetEngine().Static("/assets", "./static/dist/assets")
	//engine.GetEngine().StaticFile("/favicon.ico", "./static/favicon.ico")
	//engine.GetEngine().StaticFile("/", "./static/dist/index.html")
	srv = &http.Server{
		Addr:    ":" + *db.CliName,
		Handler: engine.GetEngine()}
	go func() {
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("listen: %s\n", err)
		}
	}()

}
func Watch(watch *fsnotify.Watcher) {
	configPath := filepath.Join(fileUtils.GetProjectPath() + "/config/")
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	fileUtils.WatchFile(watch, configPath, func(ev fsnotify.Event) {
		if ev.Op&fsnotify.Write == fsnotify.Write {
			if err := srv.Shutdown(ctx); err != nil {
				log.Fatal("Server Shutdown:", err)
			}
			log.Println("Server Exiting")
			db.InitTomlConfig()
			SetGinEngine()
		}
	})
	select {}

}

func init() {
	configFilePath := filepath.Join(fileUtils.GetProjectPath() + "/config/config.toml")
	if !fileUtils.FileDirExist(configFilePath) {
		model.Encoder(configFilePath)
	}
	db.SetConfigPath(configFilePath)

}
func main() {
	//grpc
	//server := grpcUtils.NewGrpcGinServer()
	//server.RegisterServer(func(s grpc.ServiceRegistrar) {
	//	gameObj.RegisterGameHandleServer(s, &gameHandler.GameHandle{})
	//	userInfo.RegisterUserHandleServer(s, &userHandler.UserHandle{})
	//})
	//house := finish.NewFinishedHouse(finish.SetGinGrpc(server))
	//go house.RunGrpcServer(":8083")
	gin.SetMode(gin.ReleaseMode)
	watch, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}
	defer watch.Close()
	SetGinEngine()

	go Watch(watch)
	for _, f := range service.NsqHandles {
		go f()
	}

	// 等待中断信号以优雅地关闭服务器（设置 5 秒的超时时间）
	quit := make(chan os.Signal)
	signal.Notify(quit, os.Interrupt)
	<-quit
	log.Println("Shutdown Server ...")
}
